package com.hzlj.position.locate.differentiation.positionWarningHandle;

import cn.hutool.core.util.ObjectUtil;
import com.hzlj.position.locate.common.dto.position.PositionHandleDTO;
import com.hzlj.position.locate.common.dto.position.PositionQuerySimpleResultDTO;
import com.hzlj.position.locate.common.enums.DifferentiationDataType;
import com.hzlj.position.locate.dao.PositionDao;
import com.hzlj.position.locate.differentiation.DifferentiationService;
import com.hzlj.position.locate.service.DifferentiationConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.hzlj.position.locate.common.enums.DifferentiationDataType.POSITION_WARNING_HANDLE;

/**
 * 定位告警
 */
@Slf4j
@Service
public class PositionWarningHandle implements DifferentiationService {
    @Resource
    private DifferentiationConfigService config;
    @Resource
    private PositionDao positionDao;

    @Override
    public DifferentiationDataType getType() {
        return POSITION_WARNING_HANDLE;
    }

    /**
     * 异常处理
     */
    public void handle(PositionHandleDTO dto) {
        //系统处理的记录不再做任何处理，避免循环处理
        if (Boolean.TRUE.equals(dto.getAutoHandle())) {
            return;
        }
        List<PositionQuerySimpleResultDTO> positions = dto.getKeys().stream()
                .map(e -> this.positionDao.getSimplePosition(e.getId(), e.getPositionTime()))
                .filter(e -> ObjectUtil.isNotEmpty(e.getHandleTime()))
                .collect(Collectors.toList());
        this.handlePositions(positions, dto);
    }

    /**
     * 异常处理
     */
    public void handlePositions(List<PositionQuerySimpleResultDTO> positions, PositionHandleDTO handle) {
        if (ObjectUtil.isEmpty(positions)) {
            return;
        }
        //分组
        Map<DifferentiationService, List<PositionQuerySimpleResultDTO>> positionsByService = positions.stream()
                .filter(e -> config.getService(this, getType(), e.getJgCode()) != null)
                .collect(Collectors.groupingBy(e -> config.getService(this, getType(), e.getJgCode())));
        //通知
        positionsByService.forEach((k, v) -> {
            ((PositionWarningHandle) k).handlePositions(v, handle);
        });
    }
}
